package framework.view.components.scrollbar
{
import flash.display.InteractiveObject;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.Rectangle;

import framework.proxy.ComponentProxy;

/**
 * ScrollerBarProxy
 * @author jliang
 *
 */
public class ScrollerBarProxy extends ComponentProxy
{
	//==========================================================================
	//  Constructor
	//==========================================================================
	public function ScrollerBarProxy()
	{
		super();
	}
	
	protected var con:InteractiveObject;
	
	protected var realRect:Rectangle;
	
	protected var showRect:Rectangle;
	
	protected var bg:MovieClip;
	
	protected var thumb:MovieClip;
	
	override public function parse(target:MovieClip):void
	{
		super.parse(target);
		
		bg = skin.bg;
		thumb = skin.thumb;
		
		thumb.buttonMode = true;
		thumb.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
	}
	
	public function setTarget(con:InteractiveObject, showRect:Rectangle = null):void
	{
		this.con = con;
		this.showRect = showRect;
		
		realRect = new Rectangle(0, 0, con.width, con.height);
		
		if (!this.showRect)
		{
			this.showRect = new Rectangle(0, 0, con.width, bg.height);
		}
		
		thumb.height = int(bg.height * (this.showRect.height / con.height));
		
		this.con.scrollRect = this.showRect.clone();
		
		updateHandler(null);
	}
	
	protected function mouseDownHandler(event:Event):void
	{
		thumb.removeEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
		thumb.stage.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
		
		thumb.addEventListener(Event.ENTER_FRAME, updateHandler);
		
		thumb.startDrag(false, new Rectangle(0, 0, 0, bg.height - thumb.height));
	}
	
	protected function mouseUpHandler(event:Event):void
	{
		thumb.stage.removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
		thumb.removeEventListener(Event.ENTER_FRAME, updateHandler);
		
		thumb.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
		
		thumb.stopDrag();
		
		updateHandler(null);
	}
	
	protected function updateHandler(event:Event):void
	{
		var rect:Rectangle = con.scrollRect;
		rect.y = int((realRect.height - showRect.height) * (thumb.y / (bg.height - thumb.height)));
		con.scrollRect = rect;
	}
}
}





